<template>
  <div class="body">
    <div class="search">
      <van-search
        v-model="keys"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
        <template #left>
          <van-icon name="arrow-left" size=".5rem" @click="$router.go(-1)" />
        </template>
      </van-search>
    </div>
    <div class="history">
      <div class="history_title">
        <h3>历史记录</h3>
        <van-icon name="delete" color="#ccc" size=".3rem" @click="deleleHistory" v-if="lostrogeKey.length" />
      </div>
      <div class="item_history" v-for="keySearch in lostrogeKey" :key="keySearch" @click="histroyClick(keySearch)">
        {{ keySearch }}
      </div>
    </div>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'
export default {
  data () {
    return {
      keys: '',
      lostrogeKey: localStorage.getItem('searchKey') ? JSON.parse(localStorage.getItem('searchKey')) : []
    }
  },
  methods: {
    onSearch () {
      if (this.keys.trim() === '') {
        Toast('不能搜索为空')
      } else {
        // 找缓存获取数据
        let keySearch = localStorage.getItem('searchKey') ? JSON.parse(localStorage.getItem('searchKey')) : []
        keySearch.unshift(this.keys)
        // 长度
        keySearch = keySearch.slice(0, 6)
        keySearch = [...new Set(keySearch)]
        // 存入缓存中
        localStorage.setItem('searchKey', JSON.stringify(keySearch))

        // 去搜索列表页
        this.$router.push({
          path: '/searchList',
          query: {
            keys: this.keys
          }
        }
        )
      }
    },
    // 删除历史几率
    deleleHistory (keys) {
      Dialog.confirm({
        title: '温馨提示',
        message: '确定清空历史数据'
      })
        .then(() => {
          localStorage.removeItem('searchKey')
          this.$router.go(0)
        })
        .catch(() => {
          // on cancel
        })
    },
    // 点击历史记录搜索
    histroyClick (keys) {
      this.keys = keys
      this.onSearch()
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  height: 100vh;
  background-color: #fff;
}
.history {
  padding: 0.533333rem 0.373333rem;
  h3 {
    font-size: 0.4rem;
    color: #9999;
  }
  &_title {
    display: flex;
    justify-content: space-between;
  }
}
.item_history {
  display: inline-block;
  width: 2.4rem;
  height: 0.8rem;
  padding: 0 0.2rem;
  text-align: center;
  line-height: 0.8rem;
  margin: 0.266667rem 0.266667rem 0 0;
  background-color: #f2f2f2;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  border-radius: 4px;
  font-size: 0.266667rem;
  color: #333;
  font-weight: 600;
}
</style>
